package com.link.base.base.wechat.service;

import com.link.base.base.common.model.Attachment;
import com.link.base.base.common.service.AttachmentService;
import com.link.base.base.wechat.dao.mybatis.mapper.WxImageMapper;
import com.link.base.base.wechat.model.ImgGroup;
import com.link.base.base.wechat.model.WxImage;
import com.link.base.core.basic.util.YmlConstants;
import com.link.base.wechat.mpnews.util.ArticleUtil;
import com.link.base.wechat.wxplatform.model.WxPlatform;
import com.link.base.wechat.wxplatform.service.WxPlatformService;
import com.link.base.wechat.wxtoken.service.WxTokenService;
import com.link.core.basic.dao.mapper.BasicMapper;
import com.link.core.basic.service.BasicServiceImpl;
import com.link.core.basic.service.ServiceException;
import com.link.core.cllog.LCLogger;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 微信公众号图片素材实现类
 *
 * @author lujiang
 * @date 2019/02/26 11:00
 */
@Service
public class WxImageServiceImpl  extends BasicServiceImpl<WxImage> implements WxImageService {
    @Resource
    private ImgGroupService imgGroupService;
    @Resource
    private WxImageMapper wxImageMapper;
    @Resource
    private ArticlesService articlesService;
    @Resource
    private AttachmentService attachmentService;
    @Resource
    private WxPlatformService wxPlatformService;
    @Resource
    private WxTokenService wxTokenService;

    @Override
    public BasicMapper<WxImage> getBasicMapper() {
        return wxImageMapper;
    }


    @Transactional(rollbackFor = ServiceException.class)
    @Override
    public void deleteimage(WxImage entity) {
        try {
            WxImage image = this.queryById(entity.getId());
            Long groupId = 2L;
            if (!groupId.equals(image.getGroupId())) {
                ImgGroup imggroup = imgGroupService.queryById(image.getGroupId());
                imggroup.setCount(imggroup.getCount() - 1);
                imgGroupService.update(imggroup);
            }
            this.deleteById(entity);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            LCLogger.withException(e);
        }
    }

    @Transactional(rollbackFor = ServiceException.class)
    @Override
    public Map<String, Object> updateImage(WxImage entity) {
        Map<String, Object> map = new HashMap<String, Object>(16);
        try {
            WxImage image = this.queryById(entity.getId());
            if (null != image.getGroupId() && !image.getGroupId().equals(entity.getGroupId())) {
                ImgGroup imggroup = imgGroupService.queryById(entity.getGroupId());
                imggroup.setCount(imggroup.getCount() + 1);
                imgGroupService.update(imggroup);
                Long imgGroupId = 2L;
                if (!imgGroupId.equals(image.getGroupId())) {
                    ImgGroup group = imgGroupService.queryById(image.getGroupId());
                    group.setCount(group.getCount() - 1);
                    imgGroupService.update(group);
                }
            }
            this.update(entity);
            map.put("success", true);
        } catch (Exception e) {
            map.put("success", false);
            LCLogger.withException(e);
        }
        return map;
    }

    @Transactional(rollbackFor = ServiceException.class)
    @Override
    public void batchUpdateImage(List<WxImage> wxImageList) throws Exception {
        for (WxImage entity:wxImageList) {
            WxImage image = this.queryById(entity.getId());
            if (null != image.getGroupId() && !image.getGroupId().equals(entity.getGroupId())) {
                ImgGroup imggroup = imgGroupService.queryById(entity.getGroupId());
                imggroup.setCount(imggroup.getCount() + 1);
                imgGroupService.update(imggroup);
                if (!(image.getGroupId().equals(2L))) {
                    ImgGroup group = imgGroupService.queryById(image.getGroupId());
                    group.setCount(group.getCount() - 1);
                    imgGroupService.update(group);
                }
            }
            this.update(entity);
        }
    }

    @Override
    public Map<String, Object> uploadImg(WxImage wxImage) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>(16);
        // 根据附件id 查询附件
        Attachment attachment = attachmentService.queryById(Long.valueOf(wxImage.getTempMaterialUrl()));
        // 校验唯一性
        WxImage image = new WxImage();
        image.setLoginCorpId(wxImage.getLoginCorpId());
        image.setFilename(attachment.getAttachmentOriginal());
        image.setPageFlag(false);
        List<WxImage> images = this.queryByExamplePage(image);
        if (images.size() > 0) {
            throw new ServiceException("WECHAT-014", attachment.getAttachmentOriginal());
        }
        //拼接图片路径
        String imageurl = YmlConstants.getPortalShareFileDir() + attachment.getAttachmentFilePath();
        // 设置图片信息
        wxImage.setWxId(wxImage.getWxId());
        wxImage.setFilename(attachment.getAttachmentOriginal());
        wxImage.setGroupId(wxImage.getGroupId());
        wxImage.setCreDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Calendar.getInstance().getTime()));
        String type = "image";
        //判断wxId是否为空，不为空进行微信相关操作
        if (StringUtils.isNotBlank(wxImage.getWxId())) {
            // 目的是获取token
            WxPlatform wxPlatform = new WxPlatform();
            wxPlatform.setId(Long.valueOf(wxImage.getWxId()));
            wxPlatform = wxPlatformService.queryById(wxPlatform);
            String accessToken = wxTokenService.getWxAccessTokenByAppId(wxPlatform.getWx_app_id()).getAccess_token();
            // 图片同步微信服务器
            map = ArticleUtil.uploadMaterial(accessToken,type,imageurl);
            String mediaId = "media_id";
            if (null != map.get(mediaId)) {
                wxImage.setThumbMediaId((map.get(mediaId).toString()));
                wxImage.setResult(map.get(mediaId).toString());
            }
        }
        // 修改是否成功状态
        wxImage.setIsSuccess("Y");
        wxImage.setTempMaterialUrl(attachment.getAttachmentFilePath());
        Long groupIda = 1L;  //所有分组 的分组id
        Long groupIdb = 2L;  //未分组 的分组id
        if (null == wxImage.getGroupId() || groupIda == wxImage.getGroupId()) {
            wxImage.setGroupId(groupIdb);
        }
        this.insert(wxImage);
        wxImage = this.queryById(wxImage);
        if (null != wxImage.getGroupId()
                && !groupIda.equals(wxImage.getGroupId()) && !groupIdb.equals(wxImage.getGroupId())) {
            ImgGroup imggroup = imgGroupService.queryById(wxImage.getGroupId());
            // 分组下的图片数量加1
            imggroup.setCount(imggroup.getCount() + 1);
            imgGroupService.update(imggroup);
        }
        map.put("newRow", wxImage);
        return map;
    }

    @Override
    public Map<String, Object> removeImg(Long id) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>(16);
        // 获取图片对象
        WxImage  wxImage = this.queryById(id);
        // 获取token
        WxPlatform wxPlatform = new WxPlatform();
        wxPlatform.setId(Long.valueOf(wxImage.getWxId()));
        WxPlatform platform = wxPlatformService.queryById(wxPlatform);
        String accessToken = wxTokenService.getWxAccessTokenByAppId(platform.getWx_app_id()).getAccess_token();
        // 删除素材数据
        int result = ArticleUtil.deleteArticle(accessToken,String.valueOf(wxImage.getThumbMediaId()));
        Long groupId = 2L;
        if (1 == result) {
            if (!groupId.equals(wxImage.getGroupId())) {
                ImgGroup imggroup = imgGroupService.queryById(wxImage.getGroupId());
                imggroup.setCount(imggroup.getCount() - 1);
                imgGroupService.update(imggroup);
            }
            this.deleteById(wxImage);
        } else {
            throw new ServiceException("WECHAT-015");
        }
        return map;
    }
}
